var express = require('express');
var md5 = require("md5")
var router = express.Router();

/* GET users listing. */

var user = require("../bin/UserDAO.js");

// 查询用户名/手机号是否重复
router.post("/check",(req,res)=>{
  // console.log(req.body)
  if(req.body.name){
    user.findOne({name:req.body.name})
    .then(data=>{
      if(data){
        // console.log(data)
        res.json({err:1,msg:"用户名重复"})
      }else{
        res.json({err:0,msg:"ok"})
      }
    })
  }else{
    user.findOne({tel:req.body.tel})
    .then(data=>{
      if(data){
        // console.log(data)
        res.json({err:2,msg:"手机号已经被注册"})
      }else{
        res.json({err:0,msg:"ok"})
      }
    })
  }
  
})
// 注册接口
router.post("/regist",(req,res)=>{
  // console.log(req.body);
  user.findOne({tel:req.body.tel})
  .then(data=>{
    if(data){
      res.json({err:1,msg:"电话已经被注册"})
    }else{
      user.findOne({name:req.body.name})
      .then(username=>{
        if(username){
          res.json({err:1,msg:"用户名已经存在"})
        }else{
          var u = new user({
            name:req.body.name,
            psw:md5(req.body.psw),
            country:req.body.country,
            tel:req.body.tel
          })
          u.save()
          .then(()=>{
            res.json({err:0,msg:"ok"})
          })          
        }
      })
    }
  })
})
// 国家信息
router.get("/country",(req,res)=>{
  var country = [
    "中国+86","德国+49","法国+33","奥地利+43","比利时+32","瑞士+41","希腊+30","匈牙利+36",
    "塞浦路斯+357","芬兰+358","意大利+39","罗马尼亚+420","捷克共和国+420","斯洛伐克+421",
    "葡萄牙+351","卢森堡+352","荷兰+31","丹麦+45","瑞典+46","挪威+47","波兰+48","爱尔兰+353",
    "美国+1","香港+852","澳门+853","台湾+886","澳大利亚+61","马来西亚"
  ]
  res.json({err:0,msg:country})
});

// 登录接口
router.post("/login",(req,res)=>{
  // console.log(req.body);
  user.findOne({name:req.body.name})
  .then(data=>{
    if(data){
      if(data.psw==md5(req.body.psw)){
        req.session.user=data
        res.json({err:0,msg:"登录成功"});
      }else{
        res.json({err:1,msg:"密码或用户名错误"});
      }
    }else{
      res.json({err:1,msg:"用户名不存在"});
    }
  })
});
// 判断是否登录
router.get("/islogin",(req,res)=>{
  // console.log(333)
  if(req.session.user){
    res.json({err:0,msg:req.session.user})
  }else{
    res.json({err:1,msg:"未登录"})
  }
})
// 退出登录
router.get("/logout",(req,res)=>{
  req.session.user="";
  res.json({err:0,msg:"退出成功"})
})

module.exports = router;
